<template>
  <div class="pipe-warning-container">
    <!-- 搜索 + 操作按钮区域 -->
    <div class="search-action-bar">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="预警名称">
          <el-input
            v-model="searchForm.warName"
            placeholder="请输入预警名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格展示区域 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      max-height="500"
      border
      stripe
    >
      <el-table-column prop="pipeWarId" label="预警管理ID" />
      <el-table-column prop="warName" label="预警名称" />
      <el-table-column prop="warPercent" label="预警百分比" />
      <el-table-column
        prop="updateTime"
        label="更新时间"
        :formatter="formatDate"
      />
      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">
            修改
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <div class="pagination-bar">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageDto.page"
        :page-sizes="[5, 10, 20, 30, 50]"
        :page-size="pageDto.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>
    <!-- 新增/修改弹窗 -->
    <el-dialog
      title="新增/修改预警信息"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <el-form :model="form" :rules="rules" label-width="120px" ref="formRef">
        <el-form-item label="预警管理ID" prop="pipeWarId">
          <el-input v-model.number="form.pipeWarId" disabled />
        </el-form-item>
        <el-form-item label="预警名称" prop="warName">
          <el-input v-model="form.warName" />
        </el-form-item>
        <el-form-item label="预警百分比" prop="warPercent">
          <el-input
            v-model.number="form.warPercent"
            placeholder="请输入预警百分比"
            type="number"
            step="any"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="success" @click="handleSave">确定</el-button>
      </div>
    </el-dialog>
    <!-- 删除确认弹窗 -->
    <el-dialog title="删除确认" :visible.sync="deleteVisible" width="30%">
      <p>确定要删除该预警记录吗？此操作不可逆</p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deleteVisible = false"
          >取消</el-button
        >
        <el-button type="danger" @click="confirmDelete">确定删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "PipeWarning",
  data() {
    return {
      searchForm: {}, // 搜索表单数据
      pageDto: { page: 1, size: 10 , pipeWarning:{} }, // 分页参数
      total: 0, // 总数据量
      tableData: [], // 表格数据
      dialogVisible: false, // 新增/修改弹窗显示状态
      deleteVisible: false, // 删除确认弹窗显示状态
      deleteId: null, // 待删除记录的ID
      form: {}, // 弹窗表单数据
      rules: {
        // 表单校验规则
        warName: [
          { required: true, message: "请输入预警名称", trigger: "blur" },
        ],
        warPercent: [
          {
            required: true,
            message: "请输入预警百分比",
            trigger: "blur",
          },
          {
            type: "number",
            message: "请输入有效数字（0 - 1）",
            trigger: "blur",
            min: 0,
            max: 1,
            // 转换输入值为数字
            transform(value) {
              return Number(value);
            },
          },
        ],
      },
    };
  },
  methods: {
    formatDate(row, column) {
      const date = row[column.property];
      return date ? new Date(date).toLocaleString() : "";
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.pageDto.size = val;
      this.queryByPage();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.pageDto.page = val;
      this.queryByPage();
    },
    // 查询
    handleQuery() {
      // 合并搜索条件到分页参数
      this.pageDto.pipeWarning.warName = this.searchForm.warName;
      this.pageDto.page = 1; // 重置页码
      this.queryByPage();
    },
    // 重置查询
    resetQuery() {
      this.searchForm = {};
      this.pageDto = { page: 1, size: 10, warName: "" };
      this.queryByPage();
    },
    // 新增
    handleAdd() {
      this.form = {};
      this.dialogVisible = true;
    },
    // 编辑
    handleEdit(row) {
      this.form = { ...row };
      this.dialogVisible = true;
    },
    // 删除确认
    handleDelete(row) {
      this.deleteId = row.pipeWarId;
      this.deleteVisible = true;
    },
    // 确认删除
    confirmDelete() {
      this.$api.pipeWarningApi
        .deleteById({ pipeWarId: this.deleteId })
        .then((res) => {
          if (res.data.code === 1) {
            this.$notify.success({
              title: "成功",
              message: "删除成功！",
            });
            this.deleteVisible = false;
            this.queryByPage();
          } else {
            this.$notify.error({
              title: "错误",
              message: res.data.msg || "删除失败",
            });
          }
        })
        .catch(() => {
          this.$notify.error({
            title: "错误",
            message: "网络异常，请重试",
          });
        });
    },
    // 保存新增/修改
    handleSave() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const isEdit = !!this.form.pipeWarId;
          // 区分新增和修改接口
          const apiMethod = isEdit
            ? this.$api.pipeWarningApi.edit
            : this.$api.pipeWarningApi.add;

          apiMethod(this.form)
            .then((res) => {
              if (res.data.code === 1) {
                this.$notify.success({
                  title: "成功",
                  message: isEdit ? "修改成功！" : "新增成功！",
                });
                this.dialogVisible = false;
                this.queryByPage();
              } else {
                this.$notify.error({
                  title: "错误",
                  message: res.data.msg || (isEdit ? "修改失败" : "新增失败"),
                });
              }
            })
            .catch(() => {
              this.$notify.error({
                title: "错误",
                message: "网络异常，请重试",
              });
            });
        }
      });
    },
    // 分页查询
    queryByPage() {
      this.$api.pipeWarningApi
        .queryByPage(this.pageDto)
        .then((res) => {
          if (res.data.code === 1) {
            this.tableData = res.data.data.list;
            this.total = res.data.data.total;         
          } else {
            this.$notify.error({
              title: "错误",
              message: res.data.msg || "查询失败",
            });
          }
        })
        .catch(() => {
          this.$notify.error({
            title: "错误",
            message: "网络异常，请重试",
          });
        });
    },
  },
  mounted() {
    this.queryByPage();
  },
};
</script>
<style scoped>
.pipe-warning-container {
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
  /* 让容器可滚动（极端大屏内容少也能占满视觉） */
  min-height: calc(100vh - 40px);
}

.search-action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination-bar {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}

.el-button {
  transition: all 0.3s ease;
}

.el-button:hover {
  transform: scale(1.05);
}

.el-dialog__body {
  padding: 20px;
  line-height: 1.6;
}

/* 表格容器核心样式 */
.el-table {
  width: 100% !important;
  table-layout: fixed; /* 固定布局，按列宽计算 */
  overflow: auto; /* 内容溢出时滚动 */
}

/* 强制设置每一列宽度（根据需求调整比例） */
.el-table__column--pipeWarId {
  width: 80px; /* 预警管理ID */
}
.el-table__column--warName {
  width: 200px; /* 预警名称 */
}
.el-table__column--warPercent {
  width: 120px; /* 预警百分比 */
}
.el-table__column--updateTime {
  width: 180px; /* 更新时间 */
}
.el-table__column--operation {
  width: 120px; /* 操作列 */
}

/* 解决 Element UI 表头与内容列宽不一致问题 */
.el-table th {
  table-layout: fixed;
}
</style>
